package com.itheima.consumer.controller;


import com.itheima.consumer.domain.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/findById/{id}")
    public Goods findGoodsById(@PathVariable int id){
        System.out.println("findGoodsById.... " + id);
        // 1.调用provider服务中的接口
        // String url="http://localhost:8000/provider/findOne/"+id;
        // Goods goods = restTemplate.getForObject(url, Goods.class);
        // 从eureka 服务列表中获取客户端服务列表，参数表示的是服务id
        List<ServiceInstance> instanceList = discoveryClient.getInstances("nacos-provider");
        if(instanceList==null || instanceList.size()<0){
            return null;
        }

        //获取服务实例
        ServiceInstance serviceInstance = instanceList.get(0);

        int port = serviceInstance.getPort();
        String host = serviceInstance.getHost();
        String instanceId = serviceInstance.getInstanceId();
        System.out.println("port=|"+port+"| host=|"+host+"|  instanceId=|"+instanceId);

        String url="http://"+host+":"+port+"/goods/findOne/"+id;

        Goods goods = restTemplate.getForObject(url, Goods.class);
        return goods;


    }

}
